import 'package:geocode/geocode.dart';
import 'package:geolocator/geolocator.dart';

// import 'package:location/LocationWidget.dart';
import 'package:flutter/material.dart';

class LocationWidget extends StatefulWidget {
  const LocationWidget({super.key});

  @override
  State<StatefulWidget> createState() {
    return _LocationWidget();
  }
}

class _LocationWidget extends State<LocationWidget> {
  Position? currentLocation;

  // LocationData? currentLocation;
  String address = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: const IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: null,
        ),
        title: const Text("定位"),
        centerTitle: true,
        toolbarHeight: 50,
        backgroundColor: Colors.white,
        titleTextStyle: const TextStyle(color: Colors.blue),
      ),
      body: Column(
        children: [
          GestureDetector(
            onTap: () {
              getLocation().then((value) {
                currentLocation = value;
                getAddress(
                        currentLocation?.latitude, currentLocation?.longitude)
                    .then((value) {
                  address = value;
                });
              });
            },
            child: const Text("获取当前位置"),
          ),
          if (null != currentLocation)
            Text(
                "Location:${currentLocation?.latitude},${currentLocation?.longitude}"),
          if (currentLocation != null) Text("Address: $address"),
        ],
      ),
    );
  }

  // Future<LocationData?> getLocation() async {
  //   Location location = Location();
  //   //检查设备位置是否已启用或用户是否已手动禁用它
  //   bool serviceEnabled;
  //   //定位权限
  //   PermissionStatus permissionGranted;
  //   serviceEnabled = await location.serviceEnabled();
  //   if (!serviceEnabled) {
  //     serviceEnabled = await location.requestService();
  //     if (!serviceEnabled) {
  //       return null;
  //     }
  //   }
  //   permissionGranted = await location.hasPermission();
  //   //denied 定位服务权限被拒绝
  //   if (permissionGranted == PermissionStatus.denied) {
  //     //请求权限
  //     permissionGranted = await location.requestPermission();
  //     //granted定位服务权限已被授予
  //     if (permissionGranted != PermissionStatus.granted) {
  //       return null;
  //     }
  //   }
  //   currentLocation = await location.getLocation();
  //   return currentLocation;
  // }

  Future<Position?> getLocation() async {
    bool serviceEnabled;
    LocationPermission permission;
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error('Location services are disabled.');
    }
    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }
    currentLocation =
        await Geolocator.getCurrentPosition(forceAndroidLocationManager: true);
    return currentLocation;
  }

  Future<String> getAddress(double? lat, double? lang) async {
    if (lat == null || lang == null) return "";
    GeoCode geoCode = GeoCode();
    Address address =
        await geoCode.reverseGeocoding(latitude: lat, longitude: lang);
    return "${address.streetAddress}, ${address.city}, ${address.countryName}, ${address.postal}";
  }
}
